<template>
  <div class="bread_contains">
    <el-breadcrumb style="width: 100%;" class="app-breadcrumb" separator="/">
      <transition-group name="breadcrumb">
        <el-breadcrumb-item v-for="(item,index) in levelList" :key="item.path">
        <span v-if="item.redirect==='noRedirect'||index==levelList.length-1"
              :class="[index === levelList.length -1 ? '' : 'crumb-item']">{{ item.meta.title }}</span>
          <a v-else @click.prevent="handleLink(item)" class="crumb-item">{{ item.meta.title }}</a>
        </el-breadcrumb-item>
      </transition-group>
    </el-breadcrumb>
    <span class="header_title">{{levelList[levelList.length-1].meta.title}}</span>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        levelList: null
      }
    },
    watch: {
      $route(route) {
        // if you go to the redirect page, do not update the breadcrumbs
        if (route.path.startsWith('/redirect/')) {
          return
        }
        this.getBreadcrumb()
      }
    },
    created() {
      this.getBreadcrumb()
    },
    methods: {
      getBreadcrumb() {
        // only show routes with meta.title
        let matched = this.$route.matched.filter(item => item.meta && item.meta.title)
        const first = matched[0]

        if (!this.isDashboard(first)) {
          matched = [{path: '/index', meta: {title: '首页'}}].concat(matched)
        }

        this.levelList = matched.filter(item => item.meta && item.meta.title && item.meta.breadcrumb !== false)
        console.log(this.levelList)
      },
      isDashboard(route) {
        const name = route && route.name
        if (!name) {
          return false
        }
        return name.trim() === '首页'
      },
      handleLink(item) {
        const {redirect, path} = item
        if (redirect) {
          this.$router.push(redirect)
          return
        }
        this.$router.push(path)
      }
    }
  }
</script>

<style lang="scss" scoped>
  .bread_contains {
    width: 100%;
    padding: 16px 24px;
    background-color: #fff;

    .header_title{
      margin-top: 8px;
      display: block;
      float: left;
      margin-bottom: 0;
      padding-right: 12px;
      color: rgba(0, 0, 0, 0.85);
      font-weight: 600;
      font-size: 20px;
      line-height: 32px;
    }
  }

  .app-breadcrumb.el-breadcrumb {
    display: inline-block;
    box-sizing: border-box;
    font-size: 14px;
    color: rgba(0, 0, 0, 0.65);
    cursor: pointer;

    .crumb-item {
      color: #97a8be;
    }
  }
</style>
